<template>
  <div>

    <div class="search_box">
      <el-form :model="form" :inline="true" :size="formSize">
        <el-form-item label="渠道:">
          <!-- <el-input v-model="form.channelName" placeholder="请输入渠道名称查询" clearable /> -->
          <el-select size="mini" v-model="form.channelName" filterable class="a_select" clearable>
            <el-option v-for="(item, index) in channelList" :key="index" :label="item.nickname"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="媒体:">
          <!-- <el-input v-model="form.media" placeholder="请输入媒体名称查询" clearable /> -->
          <el-select size="mini" v-model="form.media" filterable class="a_select" clearable>
            <el-option v-for="(item, index) in mediaList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:">
          <el-input v-model="form.city" placeholder="请输入城市名称查询" clearable />
        </el-form-item>
        <el-form-item label="日期:">
          <el-date-picker v-model="form.time" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table class="el_table" :data="list" border style="width: 100%">
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="nickname" label="渠道名称" />
      <el-table-column prop="counts" label="新客户数量" />
      <el-table-column v-for="(item, index) in columnsList" :key="`tab_columns_${index}`" :label="item.name"
        :prop="item.name">
        <template slot-scope="{column,row}">{{ getNum(column, row) }}</template>
      </el-table-column>
      <!-- <el-table-column prop="visitCount" label="上门">
        <template slot-scope="{row}">{{`(${row.visitCount}) `}} {{row.visitRate + '%'}}</template>
      </el-table-column>
      <el-table-column prop="contractCount" label="签约">
        <template slot-scope="{row}">{{`(${row.contractCount}) `}} {{row.contractRate + '%'}}</template>
      </el-table-column>
      <el-table-column prop="importCount" label="进件">
        <template slot-scope="{row}">{{`(${row.importCount}) `}} {{row.importRate + '%'}}</template>
      </el-table-column>
      <el-table-column prop="contractAmount" label="签约金额" />
      <el-table-column prop="contractBrokerage" label="签约佣金" />
      <el-table-column prop="importAmount" label="在审件金额" />
      <el-table-column prop="importBrokerage" label="在审件佣金" /> -->
      <!-- <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-link type="primary" class="el_link" :id="row.id" @click="lookReport(row)">查看星级报表</el-link>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 弹框 开始 -->
    <glsx-dialog :show="showDialog" width="70%" title="客户标签统计" @close="closeDialog()">
      <div class="">
        <div class="search_box">
          <el-form :model="form" :inline="true" size="small">
            <el-form-item label="渠道:">
              <!-- <el-input v-model="form.channelName" placeholder="请输入渠道名称查询" clearable /> -->
              <el-select size="mini" v-model="form.channelName" filterable class="a_select" clearable>
                <el-option v-for="(item, index) in channelList" :key="index" :label="item.nickname"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="媒体:">
              <!-- <el-input v-model="form.media" placeholder="请输入媒体名称查询" clearable /> -->
              <el-select size="mini" v-model="form.media" filterable class="a_select" clearable>
                <el-option v-for="(item, index) in mediaList" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期:">
              <el-date-picker v-model="form.time" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="getLabelStatic">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="chart_box">
          <div class="chart" id="tagStaticChart"></div>
        </div>

      </div>
      <div slot="footer">
        <el-button size="small" @click="closeDialog()">关闭</el-button>
      </div>
    </glsx-dialog>
    <!-- 弹框 end -->

  </div>
</template>
<script>
import * as echarts from "echarts";
import { deleteChannel } from "@/api/channel/index";
import { GET_ALL_CHANNEL, GET_ALL_MEDIA } from "@/http/public";
import { GET_CUSTOMER_LABEL } from "@/http/sale";
import { ECHARTCOLOR } from "@/common/constants";
import { GET_STAR_LABEL_PAGE } from "@/http/static";
import moment from "moment";
import { deepClone } from "@/utils/util";
export default {
  name: "ChannelTable",
  props: {
    list: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      showDialog: false,
      form: {},
      formSize: "small",
      channelList: [],
      mediaList: [],
      chartColor: ECHARTCOLOR,
      columnsList: []
    };
  },
  created() {
    let max = moment().format("YYYY-MM-DD");
    let min = moment().startOf("month").format("YYYY-MM-DD");
    this.$set(this.form, "time", [min, max]);
    this.$emit("input", this.form);
    this.getChannel();
    this.getMedia();
    this.getColumns()
  },
  methods: {
    handleDelete(id) {
      console.log("handleDelete");
      this.$confirm("是否确定删除渠道?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteChannel(id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleEdit(row) {
      console.log(row);
      const { id, company, nickname } = row;
      this.$router.push({
        name: "ChannelCreate",
        params: {
          type: "edit",
          id,
          nickname,
          company,
        },
      });
    },
    async deleteChannel(id) {
      console.log(id);
      const { code } = await deleteChannel({ id });
      if (code !== 200) return;
      this.$message.success("删除成功");
      this.$parent.getChannelList();
    },

    // 查看报表
    lookReport() {
      this.getLabelStatic();
      this.showDialog = true;
    },

    // 关闭弹框
    closeDialog() {
      this.showDialog = false;
    },

    // 搜索
    search() {
      this.$parent.page.page = 1;
      this.$parent.form = this.form;
      this.$emit("search");
    },

    // 获取所有渠道
    getChannel() {
      GET_ALL_CHANNEL().then((res) => {
        this.channelList = res.data || [];
      });
    },

    // 获取所有媒体
    getMedia() {
      GET_ALL_MEDIA().then((res) => {
        this.mediaList = res.data || [];
      });
    },

    // 获取查询参数
    getParams(id) {
      let oid = id || "form";
      let oParams = deepClone(this[oid]);
      console.log(oParams);
      let n = oParams.time;
      if (n && n.length >= 0) {
        oParams.startDate = n[0];
        oParams.endDate = n[1];
      }
      delete oParams.time;
      return oParams;
    },

    // 获取label
    getLabelStatic() {
      let _this = this;
      let oParams = _this.getParams();
      GET_CUSTOMER_LABEL(oParams).then((res) => {
        let list = res.data || [];
        let xAxis = [];
        let yAxis = [];
        let o = {};
        list.map((k) => {
          xAxis.push(k.label);
          yAxis.push(k.count);
        });
        o.series = [{ name: "", data: yAxis }];
        o.xaxis = xAxis;
        o.barWidth = 50;
        let options = _this.initChartData(o, "bar", list);
        _this.initDealChart(options, "tagStaticChart");
      });
    },

    // 生成图表
    initChart(id, options) {
      var chartDom = document.getElementById(id);
      var myChart = echarts.init(chartDom);
      myChart.setOption(options);
    },

    // 生成折线图、柱状图图表
    initDealChart(oParams, id) {
      let option = {
        tooltip: {
          trigger: "axis",
          formatter: oParams.formatter || "",
        },
        legend: {
          right: "16px",
          data: oParams.legend,
        },
        grid: {
          left: "16",
          right: "26",
          bottom: "16",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            //boundaryGap: oParams.boundaryGap,
            data: oParams.xaxis,
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        color: this.chartColor,
        series: oParams.series,
      };
      //this.initChart("dealChart", option);
      this.initChart(id, option);
    },

    // 处理折线图数据
    initChartData(obj, type, list) {
      if (!obj) {
        return "";
      }
      let options = {};
      let _names = [];
      let _arr = [];
      obj.series.map((k) => {
        let m = [];
        let o = {
          type: type || "line",
          smooth: true,
          areaStyle: {},
          emphasis: {
            focus: "series",
          },
          barWidth: obj.barWidth,
        };
        k.data.map((j) => {
          j = j ? Number(j.toFixed(0)) : j;
          m.push(j);
        });
        o.name = k.name;
        o.data = m;
        o.itemStyle = {
          normal: {
            label: {
              show: true,
              position: "top",
              formatter: function (params) {
                let co = list[params.dataIndex];
                let s = co ? co.rate : "";
                return s;
              },
            },
          },
        };

        _arr.push(o);
        _names.push(k.name);
      });

      options.legend = _names;
      options.series = _arr;
      options.xaxis = obj.xaxis;
      return options;
    },

    // 获取tabble列
    getColumns() {
      GET_STAR_LABEL_PAGE().then(res => {
        console.log(res)
        this.columnsList = res.data || []
      })
    },

    // 获取数量
    getNum(column, row) {
      console.log(column)
      if (!row) {
        return 0
      }
      let list = row.channelLabelList || []
      let o = list.find(k => k.label == column.property) || {};
      return `(${o.count || 0})${o.rate || 0}%`
    },

  },
};
</script>
<style lang="scss" scoped>
.chart_box {
  .chart {
    height: 300px;
  }
}
</style>
